#
# 6.863 -- Final Project
#
# Author: Andreea Bodnari
# Contact: andreeab@mit.edu
# 5/16/11
#
#

import sys
from optparse import OptionParser

from train.ngramTrain import *
from populate.Populate import *
from evaluate.evaluateGrid import *
from evaluate.taggerEvaluation import *

def main():
    '''
    Main function for the 2-dimensional n-gram analysis project
    '''
    
    possibleCorpora = ["gutenberg", "brown", "treebank" ]
    
    use =  "Usage: %prog [options] corpus nDimGrid mDimGrid nrTrials ngramSize"
    
    parser = OptionParser(usage = use)

    parser.add_option("-b",   dest="blending", action= 'store',
                      default='coinflip',
                      help="Blending method for evaluating the n-grams. Possible options are: coinflip, markov, likelier.")
    
    (options, args) = parser.parse_args()
        
    if len(args) != 5:
        parser.print_help()
        parser.error("Incorrect number of arguments or options")
        
    blendingMethod = ''
    
    if options.blending == 'coinflip':
        blendingMethod = "coinflip"
    elif options.blending == 'likelier':
        blendingMethod = "likelier"
    elif options.blending == 'markov':
        blendingMethod = "markov"
        
    if blendingMethod == '':
        print "No input blending method. Default to coinflip."
        blendingMethod = 'coinflip'
    
    # check the corpus
    corpusName = args[0]
    
    if corpusName not in possibleCorpora:
        print "ERROR: Incorrect corpus option."
        parser.print_help()
        exit(-1)
    
    # check the grid sizes
    try:
        nDim = int(args[1])
        mDim = int(args[2])
    except:
        print "ERROR: Incorrect grid size options."
        parser.print_help()
        exit(-1)
    
    # check the number of trials
    try:
        trials = int(args[3])
    except:
        print "ERROR: Incorrect number of trials option."
        parser.print_help()
        exit(-1)
    
    # check the ngram order
    try:
        nGramOrder = int(args[4])
    except:
        print "ERROR: Incorrect value for n-gram order"
        parser.print_help()
        exit(-1)
        
    # everything went on fine, on to processing
    execute(corpusName, trials, nDim, mDim, nGramOrder, blendingMethod)
        
def execute(corpusName, trials, nDim, mDim, nGramOrder,  blendingMethod):
    
    print "training..."
    trainModel = NgramTrain(nGramOrder, None, corpusName)

    print "initializing..."
    GB = GridBuilder("likelier", trainModel, trainModel, nDim, mDim)
    evaluator = Evaluate(nDim, mDim)

    print "building..."
    for trial in range( trials):
        #construct the grid
        grid = GB.constructGrid()
        
        # find the best path in the grid starting at (0,0)
        (words, probabilities, positions)= evaluator.pathFinder(grid, (0,0))
        
        # write to file the grid with the best found path 
        # and the probability matrix
        GB.writeReadableGrid(grid, True, positions)
        GB.writeReadableGrid(grid, False)
    
    print "generating comparable sentences .... "
    trainModel.generateComparableSentences()
    
    print "evaluating..."
    taggerEvaluate = TaggerEvaluation()
    taggerEvaluate.startEvaluation()
    
if __name__ == '__main__':
    main()
